package cn.edu.hunau.controller;

import cn.edu.hunau.pojo.User;
import cn.edu.hunau.service.BackstageService;
import cn.edu.hunau.service.impl.BackstageServiceImpl;
import cn.edu.hunau.utils.JsonUtils;
import cn.edu.hunau.utils.R;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @Author 苏佳
 * @Date 2023 01 04 09 27
 **/
@WebServlet("*.backstage")
public class BackstageController extends HttpServlet {
    private BackstageService backstageService = new BackstageServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String match = req.getHttpServletMapping().getMatchValue();
        PrintWriter out = resp.getWriter();
        if("countingRegisterNumNearMonth".matches(match)){
            //拿到最近各月份的注册人数数据
            Map<String, Integer> map = backstageService.countingRegisterNum();
            out.println(JsonUtils.objectToJson(R.ok().data(map)));
        } else if ("countingOrderNearMonth".matches(match)) {
            //拿到最近各月份的订单情况
            Map<String, Map<String, Integer>> maps = backstageService.countingOrder();
            out.println(JsonUtils.objectToJson(R.ok().data(maps)));
        } else if ("topSelling".matches(match)) {
            //三大板块的销售情况
            Map<String, Integer> map = backstageService.topSellingSum();
            out.println(JsonUtils.objectToJson(R.ok().data(map)));
        }
        else if ("login".matches(match)) {
            String username = req.getParameter("username");
            String pwd = req.getParameter("pwd");
            try {
                User u =backstageService.login(username, pwd);

                //如果登录成功,将用户信息封装到Session中
                HttpSession session = req.getSession();
                session.setAttribute("LOGIN_SUPERUSER",u);
                //重定向到首页地址
//                resp.sendRedirect("index.html");
                out.println(JsonUtils.objectToJson(R.ok().data(u)));
            } catch (Exception e) {
                out.print(JsonUtils.objectToJson(R.error().message(e.getMessage())));
            }
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}
